package com.visikard.ui.fragment;

import java.util.List;

import android.content.Context;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.SearchAddressTask;
import com.visikard.item.GeoSearchItem;
import com.visikard.ui.R;

public class CBInputLocationFragment extends BaseFragment {

	public static final String TAG = "CBInputLocationFragment";
	AutoCompleteTextView cityEdt;
	ArrayAdapter<GeoSearchItem> adapter;

	private BaseTask mSearchTask;
	private String mSearchString;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.cb_input_location, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		cityEdt = (AutoCompleteTextView) getView().findViewById(R.id.kard_detail_city);
		cityEdt.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mSearchString = s.toString();
				/*
				 * cancel recently task and start new task
				 */
				if (mSearchTask != null && mSearchTask.getStatus() == Status.RUNNING)
					mSearchTask.cancel(true);
				mSearchTask = new SearchAddressTask(mHandler, false);
				mSearchTask.execute(VKRegApplication.uid, mSearchString);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		cityEdt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				cityEdt.setText(adapter.getItem(position).toString());
			}
		});

		cityEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				returnResult();
				return true;
			}
		});

		/*
		 * handle close button dedicate for using with KBKardDetailsFragment25
		 */
		getView().findViewById(R.id.kard_detail_city_clear).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager in = (InputMethodManager) getActivity().getSystemService(
						Context.INPUT_METHOD_SERVICE);
				in.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				CBDetailFragment parent = (CBDetailFragment) getParentFragment();
				parent.setLocationResultAndHideChildFragment(null);
			}
		});
	}

	void returnResult() {
		InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		in.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		if (cityEdt.getText().toString().trim() != "") {
			CBDetailFragment parent = (CBDetailFragment) getParentFragment();
			parent.setLocationResultAndHideChildFragment(cityEdt.getText().toString().trim());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case UIMessage.MSG_SEARCH_ADDRESS_COMPLETE:
				String currentText = cityEdt.getText().toString();
				List<GeoSearchItem> listResult = (List<GeoSearchItem>) msg.obj;
				/*
				 * if current user input text is equal to this task search text then we show the result
				 */
				if (listResult != null && currentText.equals(mSearchString)) {
					adapter = new ArrayAdapter<GeoSearchItem>(getActivity(), R.layout.set_location_simple_list_item,
							listResult);
					cityEdt.setAdapter(adapter);
					cityEdt.showDropDown();
				}
				return true;
		}
		return super.handleMessage(msg);
	}
}
